<template>
    <el-dialog v-loading="loading" title="截图上传" :visible.sync="visible" width="1000px" :before-close="handleClose">
        <el-row>
            <el-button-group>
                <el-button type="danger" @click="selectImage">选择图片</el-button>
                <input type="file" ref="fileInput" style="display: none"
                    accept="image/jpg, image/jpeg,image/gif , image/png, image/bmp" @change="onFileChange">

                <el-button type="primary" @click="reset">重置</el-button>
                <el-button type="primary" @click="getCropImg('png')">上传PNG</el-button>
                <el-button type="primary" @click="getCropImg('jpeg')">上传JPEG</el-button>
                <el-button type="primary" @click="zoomIn">放大</el-button>
                <el-button type="primary" @click="zoomOut">缩小</el-button>
                <el-button type="primary" @click="rotateLeft">左旋转</el-button>
                <el-button type="primary" @click="rotateRight">右旋转</el-button>
                <!-- <el-button type="primary" @click="scaleX">上下翻转</el-button>
                        <el-button type="primary" @click="scaleY">左右翻转</el-button> -->
            </el-button-group>
            <el-button-group>
                <el-button type="primary" @click="setAspectRatio(1)">16:9</el-button>
                <el-button type="primary" @click="setAspectRatio(2)">4:3</el-button>
                <el-button type="primary" @click="setAspectRatio(3)">1:1</el-button>
                <el-button type="primary" @click="setAspectRatio(4)">Free</el-button>
            </el-button-group>
        </el-row>
        <el-row>
            <div class="cutimg">
                <img class="cutimg__img" ref="image" src="" alt="请选择图片">
            </div>
        </el-row>
    </el-dialog>

</template>
<script>
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
import { cosUpload } from '@/api/kanke/textbook/material';
export default {
    name: 'CutImgUpload',
    props: {
        visible: {
            type: Boolean,
            default: false
        },
    },
    data() {
        return {
            cropper: null,
            fileName: '',
            loading: false

        }
    },
    mounted() {
        this.$nextTick(() => {
            this.cropper = new Cropper(this.$refs.image, {
                viewMode: 1,
                dragMode: 'move',
                autoCropArea: 1,
                zoomable: true,
                movable: true,
                minCanvasWidth: 10, // 允许画布宽度最小为10像素
                minCanvasHeight: 10,
                center: true,    // 居中裁剪框
                minCropBoxWidth: 10, // 裁剪框最小宽度
                minCropBoxHeight: 10,
                zoom: (event) => {
                    const newRatio = event.detail.ratio;
                    // console.log('Current zoom ratio:', newRatio);
                    // 自定义逻辑，例如阻止缩小到 10% 以下
                    if (newRatio < 0.1) {
                        event.preventDefault();
                    }
                },

            });
            this.cropper.setAspectRatio(1 / 1);
            // this.cropper.setCropBoxData({
            //     width: 686,
            //     height: 497,
            // });
        })
    },
    methods: {
        loadImage(newImageUrl) {
            const img = this.$refs.image;
            img.src = newImageUrl;

            // 等图片加载完成后重新初始化
            img.onload = () => {
                if (this.cropper) {
                    this.cropper.destroy();
                }
                this.cropper = new Cropper(img, {
                    viewMode: 1,
                    dragMode: 'move',
                    autoCropArea: 1,
                    zoomable: true,
                    movable: true,
                    minCanvasWidth: 10, // 允许画布宽度最小为10像素
                    minCanvasHeight: 10,
                    minCropBoxWidth: 10, // 裁剪框最小宽度
                    minCropBoxHeight: 10,
                    zoom: (event) => {
                        const newRatio = event.detail.ratio;
                        // 自定义逻辑，例如阻止缩小到 10% 以下
                        if (newRatio < 0.1) {
                            event.preventDefault();
                        }
                    },
                });
            };
        },
        // 调用该方法更换图片
        changeImage(newImageUrl) {
            this.loadImage(newImageUrl);
        },

        selectImage() {
            this.$refs.fileInput.click();
        },
        onFileChange(event) {
            const file = event.target.files[0];
            if (file.size > 10 * 1024 * 1024) { // 5MB
                alert('图片大小不能超过 5MB！');
                return;
            }
            if (file) {
                this.fileName = file.name
                // console.log('filename', file.name, file)
                const reader = new FileReader();
                reader.onload = (e) => {
                    this.changeImage(e.target.result); // 调用更换图片方法
                };
                reader.readAsDataURL(file);

            }
        },
        getCropImg(format = 'jpeg', quality = 0.8) {
            const croppedCanvas = this.cropper
                .getCroppedCanvas()
            if (!croppedCanvas) {
                this.$message.error('未获取到裁剪图片')
                return
            }
            const that = this;
            // 将裁剪后的画布导出为 Blob 格式，降低图片质量
            croppedCanvas.toBlob(
                (blob) => {
                    // 检查 Blob 是否生成成功
                    if (!blob) {
                        that.$message.error('图片生成失败');
                        return;
                    }
                    // console.log('Blob:', blob)

                    const formData = new FormData();
                    const fileName = that.fileName || `image.${format}`;
                    blob.name = fileName;
                    formData.append('file', blob, fileName);
                    that.uploadImage(formData);
                },
                `image/${format}`,
                quality
            );
        },

        uploadImage(formData) {
            this.loading = true;
            cosUpload(formData).then((res) => {
                this.loading = false;
                if (res.code !== 200) {
                    this.$message.error(res.msg);
                    return
                }
                this.$emit('onFinish');
            })
        },

        setAspectRatio(type) {
            switch (type) {
                case 1:
                    this.cropper.setAspectRatio(16 / 9)
                    break;
                case 2:
                    this.cropper.setAspectRatio(4 / 3)
                    break;
                case 3:
                    this.cropper.setAspectRatio(1 / 1)
                    break;
                default:
                    this.cropper.setAspectRatio(0)

            }

        },
        zoomIn() {
            this.cropper.zoom(0.1)
        },
        zoomOut() {
            const currentZoom = this.cropper.getImageData().scaleX; // 获取当前缩放比例
            const newZoom = currentZoom * 0.9; // 缩小到 90%
            this.cropper.zoomTo(newZoom); // 调整缩放比例
        },

        rotateLeft() {
            this.cropper.rotate(-45)
        },
        rotateRight() {
            this.cropper.rotate(45)
        },
        scaleX() {
            this.cropper.scaleX(-1)
        },
        scaleY() {
            this.cropper.scaleY(-1)
        },
        reset() {
            this.cropper.reset()
        },
        handleClose() {
            this.fileName = ''
            this.cropper.destroy()
            this.$emit('onFinish')
        }
    }

}
</script>
<style lang="scss" scoped>
.cutimg {
    width: 100%;
    height: 680px;
    overflow-y: hidden;

    &__img {
        width: 100%;
        height: auto;
        border: 1px solid #ccc;
        object-fit: cover;
    }
}
</style>